package com.hl.card.modular.pack.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hl.card.common.controller.BaseController;
import com.hl.card.common.persistence.model.Bibivip;
import com.hl.card.common.persistence.model.BibivipRecord;
import com.hl.card.common.util.HttpURLClient;
import com.hl.card.common.util.ResponseModel;
import com.hl.card.core.log.LogObjectHolder;
import com.hl.card.modular.pack.model.Coin;
import com.hl.card.modular.pack.model.PayVo;
import com.hl.card.modular.pack.service.IBibivipRecordService;
import com.hl.card.modular.pack.service.IBibivipService;
import com.hl.card.modular.system.service.ISysDicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
/**
 * bibivipRecord控制器
 *
 * @author fengshuonan
 * @Date 2018-09-21 15:12:15
 */
@RestController
@RequestMapping("/api/bibivipRecord")
public class BibivipRecordController extends BaseController {
    @Value("${pay.config.mchId}")
    private  String  mchId;
    @Value("${pay.config.staticUrl}")
    private  String  staticUrl;
    @Value("${pay.config.payUrl}")
    private String payUrl;
    private String PREFIX = "/packBack/bibivipRecord/";
    @Autowired
    private IBibivipRecordService bibivipRecordService;
    @Autowired
    private IBibivipService bibivipService;
    @Autowired
    ISysDicService sysDicService;

   private Logger logger= LoggerFactory.getLogger(BibivipRecordController.class);
    /**
     * 跳转到bibivipRecord首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "bibivipRecord.html";
    }
    /**
     * 跳转到添加bibivipRecord
     */
    @PostMapping("/bibivipRecord_add")
    public Object bibivipRecordAdd(BibivipRecord bibivipRecord) {



        ResponseModel responseModel = new ResponseModel();
        ResponseModel resp= (ResponseModel) surplus();
        int remain= (int) resp.getData();
        if(remain<1){
            responseModel.setStatus("0002");
            responseModel.setData("名额已满");
            return responseModel;
        }
        String recordId= UUID.randomUUID().toString().replace("-","");
        try {
            bibivipRecord.setCreteTime(new Date());
            bibivipRecord.setStatus(1);
            bibivipRecord.setRecordId(recordId);
            bibivipRecordService.saveToRedis(bibivipRecord);
            responseModel.setStatus("0001");
            responseModel.setData("创建成功");
        } catch (Exception e) {
            responseModel.setStatus("0000");
            responseModel.setData("创建失败");
            e.printStackTrace();
        }
        return responseModel;
    }
    /**
     * 跳转到修改bibivipRecord
     */
    @RequestMapping("/bibivipRecord_update/{bibivipRecordId}")
    public String bibivipRecordUpdate(@PathVariable Integer bibivipRecordId, Model model) {
        BibivipRecord bibivipRecord = bibivipRecordService.selectById(bibivipRecordId);
        model.addAttribute("item", bibivipRecord);
        LogObjectHolder.me().set(bibivipRecord);
        return PREFIX + "bibivipRecord_edit.html";
    }
    /**
     * 获取bibivipRecord列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return bibivipRecordService.selectList(null);
    }

    /**
     * 新增bibivipRecord
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(BibivipRecord bibivipRecord) {
        bibivipRecordService.insert(bibivipRecord);
        return SUCCESS_TIP;
    }
    /**
     * 删除bibivipRecord
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer bibivipRecordId) {
        bibivipRecordService.deleteById(bibivipRecordId);
        return SUCCESS_TIP;
    }
    /**
     * 修改bibivipRecord
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(BibivipRecord bibivipRecord) {
        bibivipRecordService.updateById(bibivipRecord);
        return SUCCESS_TIP;
    }
    /**
     * bibivipRecord详情
     */
    @RequestMapping(value = "/detail/{bibivipRecordId}")
    @ResponseBody
    public Object detail(@PathVariable("bibivipRecordId") Integer bibivipRecordId) {
        return bibivipRecordService.selectById(bibivipRecordId);
    }
    /**
     * bibivipRecord详情
     */
    @RequestMapping(value = "/getExitsOrders/{userid}")
    @ResponseBody
    public Object getExitsOrder(@PathVariable("userid") String userid) {
        ResponseModel responseModel = new ResponseModel();
        BibivipRecord order = bibivipRecordService.getRedisRecord(userid);
        if (null == order) {
            responseModel.setStatus("0000");
        } else {
            responseModel.setStatus("0001");
            responseModel.setData(order);
        }
        return responseModel;
    }

    @PostMapping(value = "/pay")
    @ResponseBody
    public Object pay(String userid, String openid,@RequestParam(name = "backUrl") String backUrl,String clientIp, HttpServletRequest request) {


        ResponseModel responseModel = new ResponseModel();
        BibivipRecord order = bibivipRecordService.getRedisRecord(userid);
        if(null==order){
            responseModel.setStatus("0000");
            responseModel.setData("订单已失效，重新下单");
            return responseModel;
        }
        String url = payUrl + "/requestSelectPay?";
        PayVo payVo=new PayVo();
        payVo.setMchId(mchId);
        payVo.setUserId(userid);
        payVo.setMchOrderNo(order.getRecordId()+"");
        payVo.setAmount("1000000");//单位：分
        payVo.setDisPlayAmount("10000");//单位：分
        payVo.setCurrency("cny");
        payVo.setDevice("WEB");
        payVo.setSubject("航空VIP购买支付");
        payVo.setBody("航空VIP购买支付");
        payVo.setOpenId(openid);
        payVo.setClientIp(clientIp);
        payVo.setNotifyUrl(staticUrl+"/api/bibivipRecord/payResult");
        payVo.setBackUrl(backUrl);
        payVo.setExtra("{\n" +
                "  \"productId\": \"120989823\",\n" +
                "  \"openId\": \"olnubwXHaCVYR7QYAuwBr-GXFcRE\",\n" +//注意：测试WX_JSAPI时需要预先通过其他途径获取到用户openID，这里填写的是我自己的
                "  \"sceneInfo\": {\n" +
                "    \"h5_info\": {\n" +
                "      \"type\": \"Wap\",\n" +
                "      \"wap_url\": \"http://localhost.com\",\n" +
                "      \"wap_name\": \"支付测试\"\n" +
                "    }\n" +
                "  }\n" +
                " ,\"discountable_amount\":\"0.00\"," + //面对面支付扫码参数：可打折金额 可打折金额+不可打折金额=总金额
                "  \"undiscountable_amount\":\"0.00\"," + //面对面支付扫码参数：不可打折金额
                "}");
        payVo.setRedirectUrl( "https://m.bibi321.com");
        String param=JSON.toJSONString(payVo);
        Map<String, String> params = new HashMap<>();
        params.put("params", param);
        logger.info("pay"+url);
        logger.info(param);
        try {
            //String s = HttpClientTool.doPost(url, params);
            String s = HttpURLClient.post(params, url);
            responseModel = JSON.parseObject(s, ResponseModel.class);
            if(responseModel.getStatus().equals("0001")){
                bibivipRecordService.insertAllColumn(order);
                Bibivip bibivip=new Bibivip();
                BigDecimal bigDecimal=new BigDecimal("10000");
                Calendar calendar = Calendar.getInstance();
                Date date = new Date(System.currentTimeMillis());
                calendar.setTime(date);
                calendar.add(Calendar.YEAR, 1);
                date = calendar.getTime();
                bibivip.setIdcard(order.getIdcard());
                bibivip.setName(order.getName());
                bibivip.setPassport(order.getPassport());
                bibivip.setBalance(bigDecimal);
                bibivip.setCreateTime(new Date());
                bibivip.setExpiryTime(date);
                bibivip.setUserid(order.getUserid());
                Wrapper<Bibivip> warpObject=new EntityWrapper<>();
                warpObject.eq("userid",order.getUserid());
                int count= bibivipService.selectCount(warpObject);
                if(count>0){
                    bibivipService.insert(bibivip);
                }
            }
            return responseModel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @PostMapping(value = "/payResult")
    @ResponseBody
    public String payResult(String payOrderId, String amount, String mchId, String mchOrderNo, String subject, String channelAccount, String paySuccTime
                          , String sign, String channelOrderNo, String backType, String param1,
                            String param2, String clientIp, String currency, String device, String channelId, String status, HttpServletResponse response
            ){
        if(status.equals("2")){
            Wrapper<BibivipRecord> warp=new EntityWrapper<>();
            warp.eq("record_id",mchOrderNo);
            BibivipRecord order = bibivipRecordService.selectOne(warp);
            order.setStatus(2);
            order.setPlatformAccount(channelAccount);
            bibivipRecordService.updateById(order);
            return "success";
        }else{
            return "fail";
        }
    }

    @GetMapping (value = "/surplus")
    @ResponseBody
    public Object surplus() {
        String max="50";
        Map<String, Object> hkVipMax = sysDicService.selectListByCodeNo("HKVIP", "MAX");
        if(hkVipMax != null) {
             max = (String) hkVipMax.get("dicValue");
        }
        int total = Integer.parseInt(max);
        ResponseModel responseModel=new ResponseModel();
        responseModel.setStatus("0001");
        Wrapper<BibivipRecord> warp=new  EntityWrapper<>();
        warp.eq("status",2);
        int count = bibivipRecordService.selectCount(warp);
        responseModel.setData(total-count);
        return responseModel;
    }

}
